package com.woniu.product.listener;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.rabbitmq.client.Channel;
import com.woniu.common.dto.ForOrderProductDTO;
import com.woniu.product.service.ZyProductService;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.woniu.common.constant.FinanceConstant.Queue.PRODUCT_QUEUE;

/**
 * @author ltyipx
 * @version 1.0
 * @description:TODO
 * @date 2024/8/9 14:05
 */

@Component
public class ProductListener {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private ZyProductService productService;
    @SneakyThrows
    @RabbitListener(queues = PRODUCT_QUEUE)
    public void product(String msg, Message message, Channel channel){
        String token = message.getMessageProperties().getMessageId();
        try {
            if(redisTemplate.delete(token)){
                JSONObject jsonObject = JSON.parseObject(msg);
                List<ForOrderProductDTO> productList = jsonObject.getList("products", ForOrderProductDTO.class);
                productService.updateStock(productList);
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            redisTemplate.opsForValue().set(token,token,20, TimeUnit.MINUTES);
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
        }
    }
}
